﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using System.Collections;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Animation;
using Windows.Data.Xml.Dom;
using Windows.UI.Xaml.Media.Imaging;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class studyCards1 : StudyTime_1.Common.LayoutAwarePage 
    {

        public List<studyCard> cardList = new List<studyCard>();
        private static StorageFile storage;

        private static string fileName;
        private static string filePath;

        private int currItem = 0;

        public bool listMade = false;
        
        //Checks position of card if answer is showing.
        private bool answShowing = false;


        Image tempImage = new Image();
        BitmapImage tempBitmap = new BitmapImage();

        Uri imagePath;

        public studyCards1()
        {
            this.InitializeComponent();
            checkset();
        }

        private void checkset()
        {
            if (App.fileInSet == true)
            {
                var st = App.fileInStorage as StorageFile;

                storage = st;

                loadData(cardList);

                App.fileInSet = false;

            }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }


        async private void appendData()
        {

            var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
            Stream inStream = file.AsStreamForRead();
            Stream outStream = file.AsStreamForWrite();
            //card = serializer.ReadObject(inStream) as List<studyCard>;



        }


        async private void loadData(List<studyCard> card)
        {

            //convLength = 0;
            //currPage = 0;
            cardList.Clear();
            currItem = 0;
            {

                StorageFolder storageFolder = KnownFolders.VideosLibrary;


                {
                    try
                    {


                        DataContractSerializer serializer = new DataContractSerializer(typeof(List<studyCard>));

                        var file = await storage.OpenAsync(FileAccessMode.Read);
                        Stream inStream = file.AsStreamForRead();

                        card = serializer.ReadObject(inStream) as List<studyCard>;

                        foreach (studyCard studyCards in card)
                        {
                            cardList.Add(studyCards);

                        }

                        listMade = true;
                        errorBox.Text = "";
                        cardBox.Text = cardList[0].question.ToString();

                        if (cardList[0].picture != null)
                        {
                            setImage(0, false);
                        }
                        else
                        {
                            setImage(currItem, true);
                        }

                    }
                    catch (IOException)
                    {

                    }
                    catch (SerializationException)
                    {
                        errorBox.Text = "Please select a file that was created with the StudyCards app.";
                    }
                }
            }
        }

      

       public async void selection()
        {
            {
                {

                    FileOpenPicker openPicker = new FileOpenPicker();
                    openPicker.ViewMode = PickerViewMode.List;
                    openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
                    openPicker.FileTypeFilter.Add(".studycardxml");
                    storage = await openPicker.PickSingleFileAsync();

                    if (null != storage)
                    {
                        // Application now has read/write access to the picked file
                        fileName = storage.Name;
                        filePath = storage.Path;
                        loadData(cardList);
                        //questions.Text = fileName + " Click Load if this is the correct File";
                        errorBox.Text = "";

                    }
                    else
                    {
                        errorBox.Text = "File was not returned";
                        
                    }
                }


            }
        }



        private void selectCards_Click(object sender, RoutedEventArgs e)
        {
            selection();
        }

        private void flipBack_Click(object sender, RoutedEventArgs e)
        {
            if (imgScroll.Visibility == Visibility.Visible)
            {
                imgScroll.Visibility = Visibility.Collapsed;
                imagebttn.Content = "Image";
            }

            if (listMade != false)
            {
                if (currItem > 0)
                {
                    errorBox.Text = "";
                    cardBox.Text = cardList[currItem].question.ToString();
                    setImage(currItem, false);
                }
            }

            else
            {
                errorBox.Text = "Please select study cards. Use Select Cards button.";
                setImage(currItem, true);
            }

        }

        private void previous_Click(object sender, RoutedEventArgs e)
        {
            if (imgScroll.Visibility == Visibility.Visible)
            {
                imgScroll.Visibility = Visibility.Collapsed;
                imagebttn.Content = "Image";
            }
            if (currItem > 0)
            {
                if(currItem <= cardList.Count)
                {
                    currItem--;
                    errorBox.Text = "";
                    cardBox.Text = cardList[currItem].question.ToString();
                    setImage(currItem, false);
                }
                if (currItem >= cardList.Count - 1)
                {
                    currItem = cardList.Count - 1;
                    errorBox.Text = "";
                    cardBox.Text = cardList[currItem].question.ToString();
                    setImage(currItem, false);
                }
                
            }

            else
            {
                //definition.Text = "";
                // item.Text = cardList[0].question.ToString();
                currItem = -1;
                errorBox.Text = "Beginning of the Deck, press next for more cards.";
                cardBox.Text = "";
                setImage(currItem, true);
            }

        }

        private void check_Click(object sender, RoutedEventArgs e)
        {

            FlipCard();

            //if (imgScroll.Visibility == Visibility.Visible)
            //{
            //    imgScroll.Visibility = Visibility.Collapsed;
            //    imagebttn.Content = "Image";
            //}
            //if (listMade != false)
            //{

            //    cardBox.Text = cardList[currItem].answer.ToString();
            //    setImage(currItem,false);
            //    errorBox.Text = "";
            //}
            //else
            //{
            //    errorBox.Text = "Please select study cards. Use Select Cards button.";
            //    setImage(currItem, true);
            
        }

        private void FlipCard()
        {
            if (answShowing == false)
            {
                if (imgScroll.Visibility == Visibility.Visible)
                {
                    imgScroll.Visibility = Visibility.Collapsed;
                    imagebttn.Content = "Image";
                }
                if (listMade != false)
                {

                    cardBox.Text = cardList[currItem].answer.ToString();
                    setImage(currItem, false);
                    errorBox.Text = "";
                }
                else
                {
                    errorBox.Text = "Please select study cards. Use Select Cards button.";
                    setImage(currItem, true);
                }
                answShowing = true;
            }



            else
            {
                if (imgScroll.Visibility == Visibility.Visible)
                {
                    imgScroll.Visibility = Visibility.Collapsed;
                    imagebttn.Content = "Image";
                }

                if (listMade != false)
                {
                    if (currItem > 0)
                    {
                        errorBox.Text = "";
                        cardBox.Text = cardList[currItem].question.ToString();
                        setImage(currItem, false);
                    }
                }

                else
                {
                    errorBox.Text = "Please select study cards. Use Select Cards button.";
                    setImage(currItem, true);
                }
                answShowing = false;
            }
        }
 

        private void next_Click(object sender, RoutedEventArgs e)
        {
            if (imgScroll.Visibility == Visibility.Visible)
            {
                imgScroll.Visibility = Visibility.Collapsed;
                imagebttn.Content = "Image";
            }


            if (currItem < cardList.Count - 1)
            {
                currItem++;
                errorBox.Text = "";
                cardBox.Text = cardList[currItem].question.ToString();
                setImage(currItem, false);

            }
            else
            {
                currItem = cardList.Count ;
                errorBox.Text = "You reached the end of the deck.";
                cardBox.Text = "";
                setImage(currItem, true);
            }
        }

       async private void setImage(int image,bool end)
        {
            byte[] tmp = new byte[1];;
            byte[] blank = new byte[1];;
         
            if (end == false)
            {
                
                 tmp = cardList[image].picture;
            }
            else
            {
                blank = new byte[1];
            }

            BitmapImage tmpImg = new BitmapImage();

            var stream = new InMemoryRandomAccessStream();

            using (var writer = new DataWriter(stream))
            {
                if (end == false && tmp != null)
                {
                    writer.WriteBytes(tmp);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    imagebttn.IsEnabled = true;
                }
                else
                {
                    writer.WriteBytes(blank);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    imagebttn.IsEnabled = false;
                }
            }
            stream.Seek(0);
            tmpImg.SetSource(stream);
            
            stImage.Source = tmpImg;
           
           await stream.FlushAsync();
        }

       private void image_Click(object sender, RoutedEventArgs e)
       {
           if (imgScroll.Visibility == Visibility.Collapsed)
           {
               popinSB.Begin();

               imgScroll.Visibility = Visibility.Visible;

               imagebttn.Content = "Back";
           }
           else
           {
               popoutSB.Begin();
               imgScroll.Visibility = Visibility.Collapsed;
               imagebttn.Content = "Image";
           }

       }
    }

    
}
